package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceMemberAdapter;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.bean.ScheduleManager;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Megan on 16/4/11.
 */
public class AttendanceMemberActivity extends Activity implements View.OnClickListener {

    private LinearLayout mLlBack;
    private LinearLayout mLlNoData;
    private LinearLayout mLlMemberManage;
    private RelativeLayout mRlAllow;
    private RelativeLayout mRlDeviation;
    private ToggleButton mTbAllow;
    private String mAllow;
    private TextView mTvAdd, mTvTitle, mTvDeviation,mTvOk;
    private ListView mLvMemberList;
    private AttendanceMemberAdapter mAdapter;
    private ArrayList<ScheduleManager> members;
    private ScheduleManager member;
    private AttendanceData attendanceData;
    private String mDeviation;
    private String mGroupName;
    private String mUserType;
    private String mContactId;

    private final int GET_IF_ALLOW_CHANGE_DEVICE = 1000;
    private final int SET_IF_ALLOW_CHANGE_DEVICE = 1001;
    private final int SET_MEMBER_DEVIATION = 1002;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_IF_ALLOW_CHANGE_DEVICE:
                    if (msg.arg1 == 0) {
                        mAllow = msg.arg2 + "";
                        setAllow(mAllow);
                    } else {
                        Toast.makeText(AttendanceMemberActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case SET_IF_ALLOW_CHANGE_DEVICE:
                    if (msg.arg1 == 0) {

                    } else {
                        Toast.makeText(AttendanceMemberActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case SET_MEMBER_DEVIATION:
                    if(msg.arg1==0){
                        member.setDeviation(mDeviation);
                        Intent attendance = new Intent(AttendanceMemberActivity.this, AttendanceCreateActivity.class);
                        attendance.putExtra("group_id", attendanceData.getGroupId());
                        attendance.putExtra("group_name",mGroupName);
                        attendance.putExtra("user_type", mUserType);
                        attendance.putExtra("contact_id", mContactId);
                        attendance.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(attendance);
                    }else{
                        Toast.makeText(AttendanceMemberActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.attendance_member_layout);
        initViews();
        getIntentData();
    }


    private void initViews() {
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_member_back);
        mLlNoData = (LinearLayout) findViewById(R.id.ll_attendance_member_no_data);
        mLlMemberManage = (LinearLayout) findViewById(R.id.ll_attendance_member_manage);
        mRlAllow = (RelativeLayout) findViewById(R.id.rl_attendance_allow_change_device);
        mRlDeviation = (RelativeLayout) findViewById(R.id.rl_attendance_deviation_change);
        mTbAllow = (ToggleButton) findViewById(R.id.tb_attendance_allow_change_device);
        mTvAdd = (TextView) findViewById(R.id.tv_attendance_member_add);
        mTvOk=(TextView) findViewById(R.id.tv_attendance_member_ok);
        mTvDeviation = (TextView) findViewById(R.id.tv_attendance_deviation_change);
        mTvTitle = (TextView) findViewById(R.id.tv_attendance_member_title);
        mLvMemberList = (ListView) findViewById(R.id.lv_attendance_member_list);
        mLlBack.setOnClickListener(this);
        mTvAdd.setOnClickListener(this);
        mTvOk.setOnClickListener(this);
        mRlAllow.setOnClickListener(this);
        mRlDeviation.setOnClickListener(this);
        mTbAllow.setChecked(false);
        mAdapter = new AttendanceMemberAdapter(this);
        mLvMemberList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                member = members.get(i);
                if(!StringUtil.isEmpty(member.getContact_id())){
                    mLvMemberList.setVisibility(View.GONE);
                    mTvAdd.setVisibility(View.GONE);
                    mTvOk.setVisibility(View.VISIBLE);
                    mTvTitle.setText(member.getUserName());
                    mDeviation=member.getDeviation();
                    mTvDeviation.setText(mDeviation + "米");
                    mLlMemberManage.setVisibility(View.VISIBLE);
                    getIfAllowChangeDevice();
                }

            }
        });
    }

    private void getIntentData() {
        members = new ArrayList<ScheduleManager>();
        Intent intent = getIntent();
        mGroupName = intent.getStringExtra("group_name");
        mUserType = intent.getStringExtra("user_type");
        mContactId = intent.getStringExtra("contact_id");
        attendanceData = (AttendanceData) intent.getSerializableExtra("attendanceData");
        if (attendanceData.getMembers() != null) {
            try {
                JSONArray jsonArray = new JSONArray(attendanceData.getMembers());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    ScheduleManager member = new ScheduleManager();
                    member.setUserId(jsonObject.getString("user_id"));
                    member.setUserName(jsonObject.getString("contact_name"));
                    member.setAvatar(jsonObject.getString("user_image"));
                    if(jsonObject.has("deviation")){
                        member.setDeviation(jsonObject.getString("deviation"));
                    }
                    if(jsonObject.has("_id")){
                        member.setContact_id(jsonObject.getString("_id"));
                    }
                    if(jsonObject.has("contact_id")){
                        member.setContactId(jsonObject.getString("contact_id"));
                    }
                    members.add(member);
                }
                mAdapter.bindData(members);
                mLvMemberList.setAdapter(mAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_member_back:
                if (mLvMemberList.getVisibility() == View.VISIBLE) {
                    JSONArray jsonArray = new JSONArray();
                    for (ScheduleManager manager : members) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("contact_name", manager.getUserName());
                            jsonObject.put("user_id", manager.getUserId());
                            jsonObject.put("user_image", manager.getAvatar());
                            jsonObject.put("_id",manager.getContact_id());
                            jsonObject.put("contact_id",manager.getContactId());
                            jsonObject.put("deviation",manager.getDeviation());
                            jsonArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Intent back = new Intent();
                    back.putExtra("members", jsonArray.toString());
                    back.putExtra("memberCount", jsonArray.length() + "");
                    setResult(RESULT_OK, back);
                    finish();
                } else {
                    mLvMemberList.setVisibility(View.VISIBLE);
                    mLlMemberManage.setVisibility(View.GONE);
                    mTvAdd.setVisibility(View.VISIBLE);
                    mTvOk.setVisibility(View.GONE);
                    mTvTitle.setText("选择成员");
                }


                break;
            case R.id.tv_attendance_member_add:
                JSONArray jsonArray = new JSONArray();
                for (ScheduleManager manager : members) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("contact_name", manager.getUserName());
                        jsonObject.put("user_id", manager.getUserId());
                        jsonObject.put("user_image", manager.getAvatar());
                        jsonObject.put("_id",manager.getContact_id());
                        jsonObject.put("contact_id",manager.getContactId());
                        jsonObject.put("deviation",manager.getDeviation());
                        jsonArray.put(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                attendanceData.setMembers(jsonArray.toString());
                attendanceData.setMemberCount(jsonArray.length()+"");
                Intent intent = new Intent(AttendanceMemberActivity.this, CloudDialerActivity.class);
                intent.setAction("attendance_member_add");
                intent.putExtra("attendanceData", attendanceData);
                intent.putExtra("group_id", attendanceData.getGroupId());
                intent.putExtra("tag_id", "0");
                intent.putExtra("tag_name", mGroupName);
                intent.putExtra("group_name", mGroupName);
                intent.putExtra("user_type", mUserType);
                intent.putExtra("contact_count", getIntent().getStringExtra("contact_count"));
                intent.putExtra("contact_id", mContactId);
                intent.putExtra("where", "cloud");
                startActivity(intent);
                break;
            case R.id.rl_attendance_allow_change_device:
                mTbAllow.toggle();
                setIfAllowChangeDevice();
                break;
            case R.id.rl_attendance_deviation_change:
                Intent deviation = new Intent(AttendanceMemberActivity.this, AttendanceDeviationActivity.class);
                deviation.putExtra("deviation", member.getDeviation());
                startActivityForResult(deviation, 100);
                break;
            case R.id.tv_attendance_member_ok:
                setMemberDeviation();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    mDeviation = data.getStringExtra("deviation");
                    mTvDeviation.setText(mDeviation + "米");
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mLvMemberList.getVisibility() == View.VISIBLE) {
                    JSONArray jsonArray = new JSONArray();
                    for (ScheduleManager manager : members) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("contact_name", manager.getUserName());
                            jsonObject.put("user_id", manager.getUserId());
                            jsonObject.put("user_image", manager.getAvatar());
                            jsonObject.put("_id",manager.getContact_id());
                            jsonObject.put("contact_id",manager.getContactId());
                            jsonObject.put("deviation",manager.getDeviation());
                            jsonArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Intent back = new Intent();
                    back.putExtra("members", jsonArray.toString());
                    back.putExtra("memberCount", jsonArray.length() + "");
                    setResult(RESULT_OK, back);
                    finish();
                } else {
                    mLvMemberList.setVisibility(View.VISIBLE);
                    mLlMemberManage.setVisibility(View.GONE);
                    mTvAdd.setVisibility(View.VISIBLE);
                    mTvOk.setVisibility(View.GONE);
                    mTvTitle.setText("选择成员");
                }
                break;
        }
        return true;
    }

    public void delAttendanceMember(int position) {
        members.remove(position);
        mAdapter.bindData(members);
    }


    private void setAllow(String notice) {
        if ("0".equals(notice)) {
            mTbAllow.setChecked(false);
        } else if ("1".equals(notice)) {
            mTbAllow.setChecked(true);
        }
    }

    private int getAllow() {
        if (mTbAllow.isChecked()) {
            mAllow = "1";
            return 1;
        } else {
            mAllow = "0";
            return 0;
        }
    }

    /**
     * 查看某个团队成员是否更换状态
     */
    private void getIfAllowChangeDevice() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_UID, member.getUserId()));
        MyDeviceMsg myDeviceMsg = new MyDeviceMsg(mHandler.obtainMessage(GET_IF_ALLOW_CHANGE_DEVICE));
        myDeviceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_DEVICES_STATUS;
        myDeviceMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(myDeviceMsg);
    }

    /**
     * 管理员打开或关闭成员可设置默认设备的开关
     */
    private void setIfAllowChangeDevice() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_UID, member.getUserId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_IS_OPEN, getAllow() + ""));
        GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(SET_IF_ALLOW_CHANGE_DEVICE));
        getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_SWITCH_SET_DEVICES;
        getMsgHttpReceiver.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
    }


    /**
     * 设置考勤成员的签到范围偏差
     */
    private void setMemberDeviation() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair("_id", member.getContact_id()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVIATION, mDeviation));
        Message message=mHandler.obtainMessage(SET_MEMBER_DEVIATION);
        message.obj = attendanceData.getGroupId();
        WithoutObjMsg getMsgHttpReceiver = new WithoutObjMsg(message);
        getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_SET_MEMBER_DEVIATION;
        getMsgHttpReceiver.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
    }


}
